package com.poizon.infrastructure.idem.starter.redis;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.poizon.infrastructure.idem.core.domain.entity.IdemEntity;
import com.poizon.infrastructure.idem.core.repo.IIdemDbStoreRepo;
import com.poizon.infrastructure.idem.core.domain.value.enums.IdemDbStoreType;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @see IdemDbStoreType#redis
 */
@Slf4j
@AllArgsConstructor
public class RedisIdemDbStoreRepo implements IIdemDbStoreRepo {
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public IdemEntity getIdemDto(String idemKey) {
        String resp = stringRedisTemplate.opsForValue().get(idemKey);
        if (StrUtil.isBlank(resp)) {
            return null;
        }
        return JSON.parseObject(resp, IdemEntity.class);
    }

    @Override
    public Boolean setIdemKey(String idemKey, IdemEntity emptyRespIdemDto, Long expireTime, TimeUnit timeUnit) {
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(idemKey, JSON.toJSONString(emptyRespIdemDto), expireTime, timeUnit);
        return b;
    }

    @Override
    public Boolean updateIdemResp(String idemKey, IdemEntity updateRespIdemDto, Long expireTime, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(idemKey, JSON.toJSONString(updateRespIdemDto), expireTime, timeUnit);
        return true;
    }

    @Override
    public Boolean delete(String idemKey) {
        return stringRedisTemplate.delete(idemKey);
    }

}
